// 1. React核心库
import React, { useEffect, useState } from 'react';

// 2. UI组件库 - 按字母顺序
import { Card, Collapse, Table, Tag, Space, Button, message, Spin } from 'antd';

// 3. 图标库
import { AppstoreOutlined, KeyOutlined, EditOutlined, DeleteOutlined, ArrowLeftOutlined } from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer } from '@ant-design/pro-components';
import type { ColumnsType } from 'antd/es/table';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { PermissionExtension } from '@/services/generated';

const { Panel } = Collapse;

interface ModulePermissions {
  module: string;
  moduleName: string;
  permissions: PermissionExtension[];
  count: number;
}

const PermissionsByModule: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [modulePermissions, setModulePermissions] = useState<ModulePermissions[]>([]);

  // 模块名称映射
  const moduleNameMap: Record<string, string> = {
    'admin': '管理后台',
    'auth': '认证系统',
    'authentication': '用户管理',
    'contenttypes': '内容类型',
    'permissions': '权限管理',
    'sessions': '会话管理',
  };

  // 获取权限数据
  const fetchPermissions = async () => {
    try {
      setLoading(true);
      await autoLoginInDev();
      
      const response = await apiClients.permissions.permissionsPermissionsList({
        page: 1,
        pageSize: 1000, // 获取所有权限
      });

      const permissions = response?.data?.items || [];
      
      // 按模块分组
      const groupedByModule: Record<string, PermissionExtension[]> = {};
      permissions.forEach(permission => {
        const module = permission.module || 'unknown';
        if (!groupedByModule[module]) {
          groupedByModule[module] = [];
        }
        groupedByModule[module].push(permission);
      });

      // 转换为数组格式
      const moduleData: ModulePermissions[] = Object.entries(groupedByModule).map(([module, perms]) => ({
        module,
        moduleName: moduleNameMap[module] || module,
        permissions: perms,
        count: perms.length,
      }));

      // 按权限数量排序
      moduleData.sort((a, b) => b.count - a.count);
      
      setModulePermissions(moduleData);
    } catch (error) {
      message.error('获取权限数据失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchPermissions();
  }, []);

  // 权限表格列定义
  const columns: ColumnsType<PermissionExtension> = [
    {
      title: '权限代码',
      dataIndex: ['permission', 'codename'],
      width: 200,
      render: (text) => <code>{text}</code>,
    },
    {
      title: '权限名称',
      dataIndex: ['permission', 'name'],
      ellipsis: true,
    },
    {
      title: 'API端点',
      dataIndex: 'api_endpoint',
      width: 200,
      render: (text) => text ? <code>{text}</code> : '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      render: (status) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '激活' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      width: 150,
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="link" 
            size="small" 
            icon={<EditOutlined />}
            href={`/permissions/permissions/detail/${record.id}`}
          >
            详情
          </Button>
          <Button 
            type="link" 
            size="small" 
            href={`/permissions/permissions/edit/${record.id}`}
          >
            编辑
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      title="按模块查看权限"
      extra={[
        <Button key="back" icon={<ArrowLeftOutlined />} href="/permissions/permissions">
          返回权限列表
        </Button>,
      ]}
    >
      <Spin spinning={loading}>
        <div style={{ marginBottom: 16 }}>
          <Card size="small">
            <Space size="large">
              <span>总模块数: <strong>{modulePermissions.length}</strong></span>
              <span>总权限数: <strong>{modulePermissions.reduce((sum, m) => sum + m.count, 0)}</strong></span>
            </Space>
          </Card>
        </div>

        <Collapse 
          defaultActiveKey={modulePermissions.length > 0 ? [modulePermissions[0].module] : []}
          size="large"
        >
          {modulePermissions.map(moduleData => (
            <Panel
              key={moduleData.module}
              header={
                <Space>
                  <AppstoreOutlined />
                  <strong>{moduleData.moduleName}</strong>
                  <Tag color="blue">{moduleData.count} 个权限</Tag>
                  <code>{moduleData.module}</code>
                </Space>
              }
            >
              <Table
                dataSource={moduleData.permissions}
                columns={columns}
                rowKey="id"
                size="small"
                pagination={{
                  pageSize: 10,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  showTotal: (total) => `共 ${total} 条权限`,
                }}
                scroll={{ x: 800 }}
              />
            </Panel>
          ))}
        </Collapse>

        {modulePermissions.length === 0 && !loading && (
          <Card>
            <div style={{ textAlign: 'center', padding: '40px 0' }}>
              <KeyOutlined style={{ fontSize: 48, color: '#ccc', marginBottom: 16 }} />
              <p style={{ color: '#999' }}>暂无权限数据</p>
            </div>
          </Card>
        )}
      </Spin>
    </PageContainer>
  );
};

export default PermissionsByModule;
